import axios from 'axios'
import { getToken } from './auth'
import { Message } from 'element-ui'
import router from '@/router'
import store from '@/store'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 统一把axios 包的对象取出data属性值才是后端返回的直接的数据对象给逻辑页面用
    return response.data
  },
  error => {
    if (error.response.status === 401) {
      // token过期
      Message.error('登录状态过期')

      store.commit('user/removeToken')

      router.push(`login?redirect=${router.currentRoute.fullPath}`)
    }
    return Promise.reject(error)
  }
)

export default service
